<template>
    <div id="root" ref="boxRef"></div>
</template>
<script setup lang="ts">
import axios from 'axios'
import 'amis/sdk/sdk.js'
import 'amis/sdk/color-picker.js'
import 'amis/sdk/rest.js'
import copy from '@/utils/clipboard'
import feedback from '@/utils/feedback'
import { http } from '@/api/request'

const props = defineProps({
    formjson: {
        type: Object,
        default: () => {
            return {}
        }
    }
})

declare const amisRequire: (module: string) => any
const amis = amisRequire('amis/embed')
const boxRef = ref(null)

const amisScoped = ref(null)

watch(
    () => props.formjson,
    (data) => {
        nextTick(() => {
            onRendering(data)
        })
    },
    { immediate: true, deep: true }
)

function onRendering(data: any) {
    const theme = 'cxd'
    amisScoped.value = amis.embed(
        '#root',
        data,
        {
            // 这里是初始 props，一般不用传。
            // locale: 'en-US' // props 中可以设置语言，默认是中文
        },
        {
            fetcher: ({ url, method, data, config, headers }: any) => {
                config.headers = headers || {}

                switch (method.toLowerCase()) {
                    case 'get':
                        return http.get(url, data, config)
                    case 'post':
                        return http.post(url, data, config)
                    default:
                        throw new Error(`Unsupported HTTP method: ${method}`)
                }
            },
            isCancel: (value: any) => axios.isCancel(value),
            copy: (content: any) => {
                copy(content)
                feedback.success('内容已复制到粘贴板')
            },

            // 用来实现通知
            notify: (type: any, msg: any) => {
                // 暂不做处理，默认系统feedback
                console.log(type, 'type')
                console.log(msg, 'msg')
            },

            // 用来实现提示
            alert: (content: any) => {
                feedback.alert(content)
            },

            theme
        }
    )

    console.log(amisScoped, 'amisScoped')
}
</script>

<style src="amis/lib/themes/cxd.css"></style>
